const baseURL = 'api/';
const request = (options) => {
	return new Promise((resolve, reject) => {
		console.log('Request options:', options); // Log request options
		uni.request({
			url: baseURL + options.url,
			method: options.method || 'GET',
			data: options.data || {},
			header: {
				'Content-Type': 'application/json',
				'Authorization': uni.getStorageSync('token') || '',
				'uuid': uni.getStorageSync('uuid') || ''
			},
			success: (res) => {
				console.log('Response:', res); // Log response
				if (res.statusCode === 200) {
					resolve(res.data);
				} else if (res.statusCode === 401) {
					// Handle 401 Unauthorized
					uni.showToast({
						title: 'Unauthorized, redirecting to login...',
						icon: 'none'
					});
					uni.redirectTo({
						url: '/pages/index/login'
					});
					reject(res.data);
				} else {
					uni.showToast({
						title: `${res.statusCode} ${res.data.error} ${res.data.message}`,
						icon: 'error'
					});
					reject(res.data);
				}
			},
			fail: (err) => {
				console.log('Request failed:', err); // Log error
				uni.showToast({
					title: err.errMsg,
					icon: 'error'
				});
				reject(err);
			}
		});
	});
};

export default request;